<template>
  <view>
    <view v-if="props.loading" :style="{ width}" class="flex-center">
      <u-loading />
    </view>
    <view v-else-if="props.preview || props.previewUrls" @tab.stop>
      <u-image
        :src="src"
        :mode="!props.height ? 'widthFix' : (props.mode || 'aspectFit')"
        :height="props.height"
        :width="props.width"
        :shape="props.shape as string"
        :border-radius="props.borderRadius"
        @tap.stop="onPreview"
      />
      <view v-if="props.label" :style="{ width }" class="py-2 text-xs text-center text-#666">
        {{ props.label }}
      </view>
    </view>
    <view v-else>
      <u-image
        :src="src"
        :mode="!props.height ? 'widthFix' : (props.mode || 'aspectFit')"
        :height="props.height"
        :width="props.width"
        :shape="props.shape as string"
        :border-radius="props.borderRadius"
      />
      <view v-if="props.label" :style="{ width }" class="py-2 text-xs text-center text-#666">
        {{ props.label }}
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">

import UImage from '@/uni_modules/vk-uview-ui/components/u-image/u-image.vue'
import ULoading from '@/uni_modules/vk-uview-ui/components/u-loading/u-loading.vue'

const props = withDefaults(defineProps<{
  src: string,
  width?: string | number
  height?: string | number
  shape?: 'square' | 'circle'
  borderRadius?: string | number
  loading?: boolean
  label?: string
  mode?: string
  previewUrls?: string[]
  preview?: boolean
}>(), {
  borderRadius: 8,
  loading: false,
  preview: false,
})

const baseUrl = import.meta.env.VITE_APP_DOWNLOAD_API

function formatUrl(url: any) {
  if (!url || typeof url !== 'string') {
    return ''
  }
  if (url.includes('://') || url.startsWith('http') || url.startsWith('data:') || url.startsWith('/static/images/') || url.startsWith('wxfile')) {
    return url
  }
  return `${baseUrl}${url}`
}

const src = computed(() => formatUrl(props.src))
const width = computed(() => (typeof props.width === 'number' ? `${props.width}rpx` : (props.width || 'auto')))

function onPreview() {
  if (!src.value) {
    return
  }
  if (!props.previewUrls) {
    // 微信部分图片预览黑屏问题解决
    uni.downloadFile({
      url: src.value,
      success: (res) => {
        uni.previewImage({
          current: res.tempFilePath, // 当前显示图片的http链接
          urls: [res.tempFilePath],
        })
      },
    })
  } else {
    const urls = (props.previewUrls ?? [src.value])
    uni.previewImage({
      urls,
      current: src.value,
    })
  }
}
</script>

<style scoped>

</style>
